﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace PIM_ATE.Mods
{
    public partial class FrmMods : Form
    {
        public FrmMods(ClsDataUser user)
        {
            InitializeComponent();
            int size = 900;
            this.Size = new Size(size, size * 3 / 4);
            this.Text = "互调测试 1.5";
            m_isLocalConfg = GDefine.IS_LOCAL_CONFIG_MOD;
            m_userObj = user;
        }

        #region UI

        SplitContainer ctl_pim_container1;
        SplitContainer ctl_pim_container2;
        CurveChart ctl_pim_ccPlot;
        DataGridView ctl_pim_dgvData;
        TextBox ctl_pim_tbLog;

        SplitContainer ctl_eng_container1;
        SplitContainer ctl_eng_container2;
        CurveChart ctl_eng_ccPlot;
        DataGridView ctl_eng_dgvData;
        TextBox ctl_eng_tbLog;

        #region Control Created

        void createModule_pim(bool visible)
        {
            int space = 5;
            int width = this.tabPage1.Width;
            int height = this.tabPage1.Height;
            int cb_heigth = gb_pim.Height;

            ctl_pim_container1 = new SplitContainer();
            ctl_pim_container1.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom);
            ctl_pim_container1.Location = new Point(0 + space, cb_heigth + space * 2);
            ctl_pim_container1.Size = new Size(width - space * 2, height - cb_heigth - space * 2);
            ctl_pim_container1.Orientation = Orientation.Horizontal;
            ctl_pim_container1.SplitterDistance = ctl_pim_container1.Height / 3;

            ctl_pim_dgvData = new DataGridView();
            ctl_pim_dgvData.BackgroundColor = SystemColors.Control;
            ctl_pim_dgvData.Dock = DockStyle.Fill;
            ctl_pim_dgvData.RowHeadersVisible = false;
            ctl_pim_dgvData.AllowUserToAddRows = false;
            ctl_pim_dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            ctl_pim_dgvData.ReadOnly = true;
            ctl_pim_dgvData.MultiSelect = false;

            ctl_pim_container2 = new SplitContainer();
            ctl_pim_container2.Dock = DockStyle.Fill;
            ctl_pim_container2.Orientation = Orientation.Horizontal;
            ctl_pim_container2.SplitterDistance = ctl_pim_container2.Height * 2 / 3;

            ctl_pim_ccPlot = new CurveChart();
            ctl_pim_ccPlot.Dock = DockStyle.Fill;

            ctl_pim_tbLog = new TextBox();
            ctl_pim_tbLog.Dock = DockStyle.Fill;
            ctl_pim_tbLog.Multiline = true;
            ctl_pim_tbLog.ReadOnly = true;
            ctl_pim_tbLog.ScrollBars = ScrollBars.Vertical;

            this.tabPage1.Text = "测试";
            this.tabPage1.Controls.Add(ctl_pim_container1);
            ctl_pim_container1.Panel1.Controls.Add(ctl_pim_dgvData);
            ctl_pim_container1.Panel2.Controls.Add(ctl_pim_container2);
            ctl_pim_container2.Panel1.Controls.Add(ctl_pim_ccPlot);
            ctl_pim_container2.Panel2.Controls.Add(ctl_pim_tbLog);
            if (!visible)
                this.tabPage1.Parent = null;
            else
                this.tabPage1.Parent = this.tab_module;
        }

        void createModule_engineering(bool visible)
        {
            int space = 5;
            int width = this.tabPage2.Width;
            int height = this.tabPage2.Height;
            int cb_heigth = gp_engineering.Height;

            ctl_eng_container1 = new SplitContainer();
            ctl_eng_container1.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom);
            ctl_eng_container1.Location = new Point(0 + space, cb_heigth + space * 2);
            ctl_eng_container1.Size = new Size(width - space * 2, height - cb_heigth - space * 2);
            ctl_eng_container1.Orientation = Orientation.Horizontal;
            ctl_eng_container1.SplitterDistance = ctl_eng_container1.Height / 3;

            ctl_eng_dgvData = new DataGridView();
            ctl_eng_dgvData.BackgroundColor = SystemColors.Control;
            ctl_eng_dgvData.Dock = DockStyle.Fill;
            ctl_eng_dgvData.RowHeadersVisible = false;
            ctl_eng_dgvData.AllowUserToAddRows = false;
            ctl_eng_dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            ctl_eng_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            ctl_eng_dgvData.MultiSelect = false;

            ctl_eng_container2 = new SplitContainer();
            ctl_eng_container2.Dock = DockStyle.Fill;
            ctl_eng_container2.Orientation = Orientation.Horizontal;
            ctl_eng_container2.SplitterDistance = ctl_eng_container2.Height * 2 / 3;

            ctl_eng_ccPlot = new CurveChart();
            ctl_eng_ccPlot.Dock = DockStyle.Fill;

            ctl_eng_tbLog = new TextBox();
            ctl_eng_tbLog.Dock = DockStyle.Fill;
            ctl_eng_tbLog.Multiline = true;
            ctl_eng_tbLog.ReadOnly = true;
            ctl_eng_tbLog.ScrollBars = ScrollBars.Vertical;

            this.tabPage2.Text = "工程";
            this.tabPage2.Controls.Add(ctl_eng_container1);
            ctl_eng_container1.Panel1.Controls.Add(ctl_eng_dgvData);
            ctl_eng_container1.Panel2.Controls.Add(ctl_eng_container2);
            ctl_eng_container2.Panel1.Controls.Add(ctl_eng_ccPlot);
            ctl_eng_container2.Panel2.Controls.Add(ctl_eng_tbLog);
            if (!visible)
                this.tabPage2.Parent = null;
            else
                this.tabPage2.Parent = this.tab_module;
        }

        void createModule_calibration(bool visible)
        {
            ctl_cal_dgvData.ReadOnly = true;
            ctl_cal_dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            ctl_cal_dgvData.MultiSelect = false;
            ctl_cal_dgvData.RowHeadersVisible = false;
            ctl_cal_dgvData.AllowUserToAddRows = false;
            ctl_cal_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            this.tabPage3.Text = "校准";
            if (!visible)
                this.tabPage3.Parent = null;
            else
                this.tabPage3.Parent = this.tab_module;
        }

        void createModule_config(bool visible)
        {
            ctl_config_dgvData.ReadOnly = true;
            ctl_config_dgvData.SelectionMode = DataGridViewSelectionMode.CellSelect;
            ctl_config_dgvData.MultiSelect = false;
            ctl_config_dgvData.RowHeadersVisible = false;
            ctl_config_dgvData.AllowUserToAddRows = false;

            this.tabPage4.Text = "配置";
            if (!visible)
                this.tabPage4.Parent = null;
            else
                this.tabPage4.Parent = this.tab_module;
        }

        void createModule_setup(bool visible)
        {
            ctl_setup_dgvData.ReadOnly = true;
            ctl_setup_dgvData.SelectionMode = DataGridViewSelectionMode.CellSelect;
            ctl_setup_dgvData.MultiSelect = false;
            ctl_setup_dgvData.RowHeadersVisible = false;
            ctl_setup_dgvData.AllowUserToAddRows = false;
            ctl_setup_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            this.tabPage5.Text = "设置";
            if (!visible)
                this.tabPage5.Parent = null;
            else
                this.tabPage5.Parent = this.tab_module;
        }

        #endregion

        #endregion


        ClsDataConfigBuilder m_pim_cfgDataBuilder;
        List<ClsDataConfig> m_pim_lstCfgData;
        DataTable m_pim_dtShow;
        List<ClsDataConfig> m_eng_lstCfgData;
        DataTable m_eng_dtShow;

        ClsDataConfigBuilder m_cfg_cfgDataBuilder;
        ProcodeINFO m_cfg_procodeObj;
        DataTable m_cfg_dtConfigItems;

        ClsDataCalibrationBuilder m_cal_builder;
        DataTable m_cal_dtShow;

        ClsDataSetupBuilder m_setup_builder;
        DataTable m_setup_dtShow;


        System.Threading.Timer m_time_now;
        FrmTips ctl_frm_message;
        PIMProcess m_processObj;
        ClsDataUser m_userObj;
        InstrumentGroup m_instr;
        string m_sRCUComName;
        string m_sKnkComName;
        bool m_isProcessStart;
        int m_running_mode;
        int m_process_mode = 0;
        bool m_isLocalConfg = false;
        float m_fMax;

        float m_plot_x_start = 0;
        float m_plot_y_start = 0;

        FrmTime ftime = null;
        ModTestMode m_ModTestMode;

        private void FrmMods_Load(object sender, EventArgs e)
        {
            createModule_pim(true);

            createModule_engineering(true);
            createModule_config(true);

            createModule_calibration(true);
            createModule_setup(true);
            btn_pim_ok.Visible = true;
            ctl_pim_cbVerConfig.Enabled = false;

            tab_module.Enabled = true;
            m_time_now = new System.Threading.Timer(evt_timer_tick, null, 0, 1000);
            IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcOther.ini");
            m_ModTestMode = (ModTestMode)Convert.ToInt32(IniFile.IniReadValue("Login", "ModTestMode", "0"));
            if (m_ModTestMode == ModTestMode.First)
            {
                toolStripStatusLabel1.Text = "一次互调测试";
            }
            else
            {
                toolStripStatusLabel1.Text = "二次互调测试";
            }
            if (GDefine.IS_PIM_SECOND) 测试类型ToolStripMenuItem.Visible = false;
            toolStripStatusLabel2.Text = string.Format("员工号：{0}      姓名：{1}      账号类型：{2}",
                                         m_userObj.sUserID, m_userObj.sUser, m_userObj.sRemark);
            toolStripStatusLabel3.Text = string.Format("设备IP:{0}      管理部门:质量", m_userObj.sEquID);
            ctl_cal_textEquID.Text = m_userObj.sEquID;

            ctl_cal_mode.SelectedIndex = 0;

            timer1.Start();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            initDataBaseNames();
            initDataInstrument();

            if (m_isLocalConfg)
            {
                ctl_main_btnSet.Text = "本地";
            }
            else
            {
                ctl_main_btnSet.Text = "刷新";
                initDataConfig();
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (m_isProcessStart) e.Cancel = true;
            base.OnClosing(e);
        }

        #region Running Event Handler

        void m_process_evt_log_handle(object sender, EventArgs e)
        {
            string sLog = sender as string;
            if (e == null)
            {
                this.Invoke(new ThreadStart(delegate
                {
                    if (m_running_mode == 0)
                    {
                        ctl_pim_tbLog.AppendText(sLog + "\r\n");
                    }
                    else if (m_running_mode == 1)
                    {
                        ctl_eng_tbLog.AppendText(sLog + "\r\n");
                    }
                    else
                    {
                        ctl_cal_textShow.AppendText(sLog + "\r\n");
                    }
                }));
            }
            else
            {
                EventLoggingArgs eLogging = e as EventLoggingArgs;
                this.Invoke(new ThreadStart(delegate
                {
                    if (eLogging.isClose)
                    {
                        if (ctl_frm_message != null)
                        {
                            ctl_frm_message.Close();
                            ctl_frm_message = null;
                        }
                        //if (ftime != null)
                        //{
                        //    ftime.Close();
                        //    ftime = null;
                        //}
                        return;
                    }

                    if (eLogging.isTips)
                    {
                        if (ctl_frm_message == null)
                        {
                            ctl_frm_message = new FrmTips(sLog);
                            ctl_frm_message.Show(this);
                        }
                        //if (ftime == null)
                        //{
                        //    ftime = new FrmTime(sLog);
                        //    ftime.evt_OK_handle += ssss;
                        //    ftime.evt_Cancel_handle += ssss2;
                        //    ftime.Show(this);
                        //}
                    }
                    else
                    {
                        if (ctl_frm_message != null)
                        {
                            ctl_frm_message.Close();
                            ctl_frm_message = null;
                        }
                        //if (ftime != null)
                        //{
                        //    ftime.Close();
                        //    ftime = null;
                        //}
                    }
                }));
            }
        }

        void ssss(object sender, EventArgs e)
        {

            m_processObj.TestStop();
            //m_process_evt_complete_all_process_handle(null, null); 
        }
        void ssss2(object sender, EventArgs e)
        {
            m_processObj.OverTest();
            //m_process_evt_complete_all_process_handle(null, null); 
        }

        void m_process_evt_complete_all_process_handle(object sender, EventArgs e)
        {
            this.Invoke(new ThreadStart(delegate
                {
                    m_isProcessStart = false;
                    setEnable(true);

                    ctl_pim_dgvData.CurrentCell = null;
                    ctl_eng_dgvData.CurrentCell = null;
                    if (sender != null)
                    {
                        AutoClosingMessageBox.Show(sender as string, "提示", 5000);
                    }

                    ctl_main_tbProSN.Text = "";
                    ctl_main_textLocalStep.Text = "";
                    ctl_main_tbProSN.Focus();
                }));
        }

        void m_process_evt_complete_process_handle(object sender, EventArgs e)
        {
            EventProcessArgs eProcess = e as EventProcessArgs;
            float fMax = (float)eProcess.processObj;
            bool bResult = eProcess.processState;
            this.Invoke(new ThreadStart(delegate
            {
                if (m_running_mode == 3)
                {
                    DateTime dt = DateTime.Now;
                    if (m_rowCalibration != null)
                    {
                        m_rowCalibration[3] = fMax.ToString();
                        m_rowCalibration[4] = dt.ToString();
                    }
                    ctl_cal_textShow.AppendText("校准值： " + fMax.ToString() + "\r\n");
                    ctl_cal_textShow.AppendText("校准时间： " + dt.ToString() + "\r\n");
                    ctl_cal_textShow.AppendText("校准完成!\r\n");
                    return;
                }

                DataTable table = m_running_mode == 0 ? m_pim_dtShow : m_eng_dtShow;
                DataGridView dgv = m_running_mode == 0 ? ctl_pim_dgvData : ctl_eng_dgvData;
                table.Rows[eProcess.processNum]["测试值"] = fMax;
                if (bResult)
                {
                    table.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentFail2;
                    dgv.Rows[eProcess.processNum].Cells["判定结果"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                    dgv.Rows[eProcess.processNum].Cells["测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                    dgv.Rows[eProcess.processNum].Cells["实时测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                }
                else
                {
                    table.Rows[eProcess.processNum]["判定结果"] = GDefine.ContentPass2;
                    dgv.Rows[eProcess.processNum].Cells["判定结果"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                    dgv.Rows[eProcess.processNum].Cells["测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                    dgv.Rows[eProcess.processNum].Cells["实时测试值"].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                }

                if (ctl_frm_message != null)
                {
                    ctl_frm_message.Close();
                    ctl_frm_message = null;
                }
            }));
        }

        void m_process_evt_set_settings_handle(object sender, EventArgs e)
        {
            JcPIMDataSettings settings = sender as JcPIMDataSettings;
            EventProcessArgs ePorcess = e as EventProcessArgs;
            this.Invoke(new ThreadStart(delegate
            {
                DataGridView dgv = m_running_mode == 0 ? ctl_pim_dgvData : ctl_eng_dgvData;
                if (ePorcess.processNum >= 0 && ePorcess.processNum < dgv.Rows.Count)
                {
                    dgv.Rows[ePorcess.processNum].Selected = true;
                    int n = (dgv.Height - dgv.ColumnHeadersHeight) / dgv.RowTemplate.Height - 1;
                    if (ePorcess.processNum > n)
                        dgv.FirstDisplayedScrollingRowIndex = ePorcess.processNum - n;
                    else
                        dgv.FirstDisplayedScrollingRowIndex = 0;
                }

                CurveChart plot = m_running_mode == 0 ? ctl_pim_ccPlot : ctl_eng_ccPlot;
                plot.Clear();
                if (settings.Mode == ImMode.Freq)
                {
                    if (settings.RXs != settings.RXe)
                        plot.SetPlotX((float)settings.RXs, (float)settings.RXe);

                    if (settings.Unit == ImUnit.dBc)
                    {
                        plot.SetPlotTitle("扫频模式", "MHz", "dBc");
                        plot.SetPlotY(-193, -93);
                    }
                    else
                    {
                        plot.SetPlotTitle("扫频模式", "MHz", "dBm");
                        plot.SetPlotY(-150, -50);
                    }
                }
                else
                {
                    plot.SetPlotTitle("点频模式", "", "");
                    plot.SetPlotX(0, settings.Time);
                    m_plot_x_start = 0;
                    m_plot_y_start = settings.Time + 10;
                }
            }));

        }

        void m_process_evt_get_results_handle(object sender, EventArgs e)
        {
            JcPIMDataResults val = sender as JcPIMDataResults;
            EventProcessArgs ePorcess = e as EventProcessArgs;
            int n = val.No;
            float p1 = val.P1;
            float f1 = val.F1;
            float p2 = val.P2;
            float f2 = val.F2;
            float im_f = val.Im_F;
            float im_v = val.Im_V;
            int n1 = val.n1;
            int n2 = val.n2;

            this.Invoke(new ThreadStart(delegate
            {
                ctl_main_lblReuslt.Text = "P1 = " + p1 + " dBm\r\nP2 = " + p2 + " dBm";

                if (m_running_mode == 3)
                {
                    float max;
                    if (!float.TryParse(ctl_cal_textMax.Text, out max))
                        max = float.MinValue;

                    if (max < im_v)
                    {
                        ctl_cal_textMax.Text = im_v.ToString();
                        float limit = 0;
                        float.TryParse(m_rowCalibration[6].ToString(), out limit);
                        if (im_v > limit)
                        {
                            ctl_cal_textPass.Text = GDefine.ContentFail2;
                            ctl_cal_textPass.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                        }
                    }

                    ctl_cal_lblPower.Text = string.Format("功率: P1= {0} dBm, P2= {1} dBm", p1, p2);
                    ctl_cal_textIMV.Text = im_v.ToString();
                    ctl_cal_textShow.AppendText(val.ToString() + "\r\n");

                    return;
                }

                CurveChart plot = m_running_mode == 0 ? ctl_pim_ccPlot : ctl_eng_ccPlot;
                DataTable table = m_running_mode == 0 ? m_pim_dtShow : m_eng_dtShow;
                TextBox text = m_running_mode == 0 ? ctl_pim_tbLog : ctl_eng_tbLog;

                text.AppendText(val.ToString() + "\r\n");
                if (n1 == 0 && n2 == 0)
                {
                    plot.Add(new PointF(n, im_v), 0);
                    if (n >= m_plot_y_start)
                        m_plot_y_start += 10;
                    plot.SetPlotX(m_plot_x_start, m_plot_y_start);
                }
                else if (n <= n1)
                {
                    plot.Add(new PointF(im_f, im_v), 0);
                }
                else
                {
                    plot.Add(new PointF(im_f, im_v), 1);
                }

                table.Rows[ePorcess.processNum]["实时测试值"] = im_v;
            }));
        }

        void evt_timer_tick(object sender)
        {
            this.toolStripStatusLabel4.Text = DateTime.Now.ToShortTimeString();
        }

        #endregion

        #region Data Init

        void initDataBaseNames()
        {
            if (m_pim_cfgDataBuilder == null)
            {
                m_pim_cfgDataBuilder = new ClsDataConfigBuilder(GDefine.DBNameMOD);
            }
            if (m_cfg_cfgDataBuilder == null)
            {
                m_cfg_cfgDataBuilder = new ClsDataConfigBuilder(GDefine.DBNameMOD);
            }
            if (m_cal_builder == null)
            {
                m_cal_builder = new ClsDataCalibrationBuilder(GDefine.DBNameMOD);
            }
            if (m_setup_builder == null)
            {
                m_setup_builder = new ClsDataSetupBuilder(GDefine.DBNameMOD);
            }
        }

        void initDataInstrument()
        {
            JcPIMInstrumentInfo[] lstInstruments = null;
            JcPIMDevicesBuilder.LoadDefaultBand(Application.StartupPath + "\\JcBandInfo.ini");

            try
            {
                lstInstruments = JcPIMDevicesBuilder.LoadDesktopInstrument(Application.StartupPath);
                if (IniFile.IniReadValue("Settings", "type", "0") == "2")
                {
                    m_instr = InstrumentGroup.RFDESKTOP;
                    toolStripStatusLabel5.Text += "纳特";
                }
                else
                {
                    m_instr = InstrumentGroup.DESKTOP;
                    toolStripStatusLabel5.Text += "紫光";
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }

            m_processObj = new PIMProcessForModule(this, lstInstruments, m_instr);
            m_processObj.evt_set_settings_handle += m_process_evt_set_settings_handle;
            m_processObj.evt_get_results_handle += m_process_evt_get_results_handle;
            m_processObj.evt_complete_process_handle += m_process_evt_complete_process_handle;
            m_processObj.evt_complete_all_process_handle += m_process_evt_complete_all_process_handle;
            m_processObj.evt_log_handle += m_process_evt_log_handle;
        }

        #endregion

        #region 测试配置

        void clearConfig()
        {
            ctl_pim_cbVerConfig.Items.Clear();
            if (m_pim_lstCfgData != null) m_pim_lstCfgData.Clear();
            if (m_pim_dtShow != null) m_pim_dtShow.Clear();

            ctl_eng_cbVerConfig.Items.Clear();
            if (m_eng_lstCfgData != null) m_eng_lstCfgData.Clear();
            if (m_eng_dtShow != null) m_eng_dtShow.Clear();

            ctl_config_cbVerConfig.Items.Clear();
            m_cfg_procodeObj = null;
            if (m_cfg_dtConfigItems != null) m_cfg_dtConfigItems.Clear();

            m_cal_builder.construct("", "");
            if (m_cal_dtShow != null) m_cal_dtShow.Clear();

            m_setup_builder.construct("");
            if (m_setup_dtShow != null) m_setup_dtShow.Clear();
        }

        bool initDataConfig()
        {
            clearConfig();

            if (m_isLocalConfg)
            {
                OpenFileDialog frmFile = new OpenFileDialog();
                frmFile.Multiselect = false;
                frmFile.InitialDirectory = Application.StartupPath + "\\config";
                if (frmFile.ShowDialog() == DialogResult.OK)
                { }
            }
            else
            {
                ctl_main_cbProCode.Items.Clear();
                var list = m_pim_cfgDataBuilder.getProcodeList();
                if (list != null)
                    ctl_main_cbProCode.Items.AddRange(list);
            }

            return true;
        }

        void refreshPIMTestVer(string[] lstVer)
        {

            string sConfigVer, sSpecVer;
            string[] sEffVer;
            m_pim_cfgDataBuilder.getEffVer(out sConfigVer, out sSpecVer, out sEffVer);
            ctl_pim_cbVerConfig.Items.AddRange(sEffVer);
            ctl_pim_cbVerConfig.Text = sConfigVer;
            ctl_pim_textVerSpec.Text = sSpecVer;
        }

        private void ctl_main_cbProCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ctl_main_cbProCode.Text == "") return;
            clearConfig();

            var lstVer = m_pim_cfgDataBuilder.constructByProcode(ctl_main_cbProCode.Text);
            refreshPIMTestVer(lstVer);
            ctl_eng_cbVerConfig.Items.AddRange(lstVer);

            var lstConfigVer = m_cfg_cfgDataBuilder.constructByProcode(ctl_main_cbProCode.Text);
            ctl_config_cbVerConfig.Items.AddRange(lstConfigVer);
        }

        #region 配置触发事件

        private void initPIMShowTable()
        {
            ctl_pim_dgvData.DataSource = null;
            for (int i = 0; i < m_pim_dtShow.Rows.Count; i++)
            {
                m_pim_dtShow.Rows[i]["测试值"] = "";
                m_pim_dtShow.Rows[i]["判定结果"] = "";
                m_pim_dtShow.Rows[i]["实时测试值"] = "";
            }
            ctl_pim_dgvData.DataSource = m_pim_dtShow.DefaultView;
            ctl_pim_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            ctl_pim_dgvData.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            for (int i = 0; i < ctl_pim_dgvData.Columns.Count; i++)
            {
                ctl_pim_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void ctl_pim_cbVerConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            downloadPIMModuleData(sender);

            IniFile.SetFileName(Application.StartupPath + "\\JcVersion.ini");
            IniFile.IniWriteValue("VersionRecord", ctl_main_cbProCode.Text, ctl_pim_cbVerConfig.Text);
        }

        void downloadPIMModuleData(object sender)
        {
            var cbVer = sender as ComboBox;
            if (cbVer.SelectedIndex == -1) return;
            string error = "";
            m_pim_cfgDataBuilder.construct(ctl_main_cbProCode.SelectedItem.ToString(),
                                           cbVer.SelectedItem.ToString());

            ctl_pim_textVerSpec.Text = m_pim_cfgDataBuilder.sVerSpec;
            m_pim_lstCfgData = m_pim_cfgDataBuilder.download(out m_pim_dtShow, ref error);
            if (m_pim_lstCfgData == null || error == "")
            {
                initPIMShowTable();
            }
        }

        private void initENGShowTable()
        {
            ctl_eng_dgvData.DataSource = null;
            for (int i = 0; i < m_eng_dtShow.Rows.Count; i++)
            {
                m_eng_dtShow.Rows[i]["测试值"] = "";
                m_eng_dtShow.Rows[i]["判定结果"] = "";
                m_eng_dtShow.Rows[i]["实时测试值"] = "";
            }
            ctl_eng_dgvData.DataSource = m_eng_dtShow.DefaultView;

            for (int i = 0; i < ctl_eng_dgvData.Columns.Count; i++)
            {
                ctl_eng_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            if (ctl_eng_dgvData.Columns[0].HeaderText != "")
            {
                var colCheck = new DataGridViewCheckBoxColumn();
                ctl_eng_dgvData.Columns.Insert(0, colCheck);
            }
            for (int i = 0; i < ctl_eng_dgvData.Rows.Count; i++)
            {
                ctl_eng_dgvData.Rows[i].Cells[0].Value = m_eng_lstCfgData[i].Enable;
            }
            ctl_eng_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            ctl_eng_dgvData.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            ctl_eng_dgvData.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        }

        private void ctl_eng_cbVerConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            downloadENGModuleData(sender);
        }

        void downloadENGModuleData(object sender)
        {
            var cbVer = sender as ComboBox;
            if (cbVer.SelectedIndex == -1) return;
            if (ctl_main_cbProCode.SelectedIndex == -1) return;
            string error = "";
            m_pim_cfgDataBuilder.construct(ctl_main_cbProCode.SelectedItem.ToString(),
                                           cbVer.SelectedItem.ToString());

            ctl_eng_textVerSpec.Text = m_pim_cfgDataBuilder.sVerSpec;
            m_eng_lstCfgData = m_pim_cfgDataBuilder.download(out m_eng_dtShow, ref error);
            if (m_eng_lstCfgData == null || error == "")
            {
                initENGShowTable();
            }
        }

        #endregion

        #endregion



        #region Menu control Event

        private void 重新登陆ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmLogin frmlgn = new FrmLogin(m_userObj);
            frmlgn.ControlBox = true;
            if (frmlgn.ShowDialog() == DialogResult.OK)
            {
                toolStripStatusLabel2.Text = string.Format("员工号：{0}      姓名：{1}      账号类型：{2}",
                                            m_userObj.sUserID, m_userObj.sUser, m_userObj.sRemark);
                toolStripStatusLabel3.Text = string.Format("设备IP:{0}      管理部门:质量", m_userObj.sEquID);
            }
        }

        private void ConfigToolStripMenuItem_Click(object sender, EventArgs e)
        { }

        private void ctl_main_btnSet_Click(object sender, EventArgs e)
        {
            initDataConfig();
        }

        private void tab_module_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        #endregion

        #region ENG control Event

        private void ctl_eng_btnModify_Click(object sender, EventArgs e)
        { }

        private void ctl_eng_btnNew_Click(object sender, EventArgs e)
        {
            FrmMConfigNew frmConfig = new FrmMConfigNew();
            frmConfig.ShowDialog();
        }

        #endregion

        #region CAL control Event

        private bool checkCalParam(DataRow dr)
        {
            try
            {
                if (Convert.ToDouble(dr[7].ToString()) <= 0)
                    return false;
                if (Convert.ToDouble(dr[8].ToString()) <= 0)
                    return false;
                if (Convert.ToDouble(dr[9].ToString()) <= 0)
                    return false;
                if (Convert.ToDouble(dr[10].ToString()) <= 0)
                    return false;
                if (Convert.ToDouble(dr[11].ToString()) <= 0)
                    return false;
            }
            catch { return false; }

            return true;
        }

        private bool checkCalControl()
        {
            if (ctl_cal_nudF1.Value == 0)
                return false;
            if (ctl_cal_nudF2.Value == 0)
                return false;
            if (ctl_cal_nudRX1.Value == 0)
                return false;
            if (ctl_cal_nudRX2.Value == 0)
                return false;
            if (ctl_cal_nudRXSTEP.Value == 0)
                return false;

            return true;
        }

        DataRow m_rowCalibration;
        private void ctl_cal_btnDownload_Click(object sender, EventArgs e)
        {
            string error = "";
            m_cal_builder.construct(ctl_main_cbProCode.Text, m_userObj.sEquID);
            if (!GDefine.IS_DOWN_CAL_MOD)
            {
                m_cal_dtShow = m_cal_builder.download(ref error);
            }
            else
            {
                m_cal_dtShow = new DataTable();
                for (int i = 1; i < 15; i++)
                    m_cal_dtShow.Columns.Add(i.ToString(), typeof(string));

            }
            if (m_cal_dtShow != null)
            {
                ctl_cal_dgvData.DataSource = m_cal_dtShow;
                ctl_cal_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                ctl_cal_dgvData.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                ctl_cal_dgvData.Columns[0].Visible = false;
                for (int i = 0; i < ctl_cal_dgvData.Columns.Count; i++)
                {
                    ctl_cal_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }

                DataRow drNew = m_cal_dtShow.NewRow();
                if (m_cal_dtShow.Rows.Count == 0)
                {
                    drNew[0] = m_userObj.sEquID;
                    drNew[1] = 0;
                    drNew[2] = 0;
                    drNew[3] = 0;
                    drNew[4] = DateTime.Parse("1900-01-01");
                    drNew[5] = "False";
                    drNew[6] = "";
                    drNew[7] = 0;
                    drNew[8] = 0;
                    drNew[9] = 0;
                    drNew[10] = 0;
                    drNew[11] = 0;
                    drNew[12] = 0;
                }
                else
                {
                    drNew.ItemArray = m_cal_dtShow.Rows[m_cal_dtShow.Rows.Count - 1].ItemArray.Clone() as object[];
                    ctl_cal_dgvData.Rows[ctl_cal_dgvData.Rows.Count - 1].Selected = true;
                    int n = (ctl_cal_dgvData.Height - ctl_cal_dgvData.ColumnHeadersHeight) / ctl_cal_dgvData.RowTemplate.Height - 1;
                    if (ctl_cal_dgvData.Rows.Count - 1 > n)
                        ctl_cal_dgvData.FirstDisplayedScrollingRowIndex = ctl_cal_dgvData.Rows.Count - 1 - n;
                    else
                        ctl_cal_dgvData.FirstDisplayedScrollingRowIndex = 0;
                }

                try
                {
                    ctl_cal_nudTxOff.Value = Convert.ToDecimal(drNew[1]);
                    ctl_cal_nudRxOff.Value = Convert.ToDecimal(drNew[2]);

                    ctl_cal_textRemark.Text = drNew[6].ToString();
                    ctl_cal_checkEff.Checked = Convert.ToBoolean(drNew[5]);

                    ctl_cal_nudF1.Value = Convert.ToDecimal(drNew[7]);
                    ctl_cal_nudF2.Value = Convert.ToDecimal(drNew[8]);

                    ctl_cal_nudRX1.Value = Convert.ToDecimal(drNew[9]);
                    ctl_cal_nudRX2.Value = Convert.ToDecimal(drNew[10]);
                    ctl_cal_nudRXSTEP.Value = Convert.ToDecimal(drNew[11]);

                    ctl_cal_nudProOffset.Value = Convert.ToDecimal(drNew[12]);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("最后的校准记录存在非法字符!(" + ex.Message + ")");
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }

        private void ctl_cal_btnUpload_Click(object sender, EventArgs e)
        {
            if (m_cal_dtShow == null) return;


            if (m_rowCalibration == null)
            {
                MessageBox.Show("请先校准");
                return;
            }

            string error = "";
            ClsDataCalibration cal = new ClsDataCalibration();
            cal.setValues(ctl_main_cbProCode.Text, m_rowCalibration);
            if (!m_cal_builder.upload(cal, ref error))
            {
                MessageBox.Show(error);
            }
            else
            {
                m_cal_dtShow.Rows.Add(m_rowCalibration);
                ctl_cal_dgvData.Rows[ctl_cal_dgvData.Rows.Count - 1].Selected = true;
                int n = (ctl_cal_dgvData.Height - ctl_cal_dgvData.ColumnHeadersHeight) / ctl_cal_dgvData.RowTemplate.Height - 1;
                if (ctl_cal_dgvData.Rows.Count - 1 > n)
                    ctl_cal_dgvData.FirstDisplayedScrollingRowIndex = ctl_cal_dgvData.Rows.Count - 1 - n;
                else
                    ctl_cal_dgvData.FirstDisplayedScrollingRowIndex = 0;

                m_rowCalibration = null;
                MessageBox.Show("上传成功");
            }
        }

        private void ctl_cal_btnModify_Click(object sender, EventArgs e)
        {
            if (m_cal_dtShow == null || m_cal_dtShow.Rows.Count == 0)
            {
                MessageBox.Show("请先下载校准");
                return;
            }

            if (!checkCalControl())
            {
                MessageBox.Show("未设置参数");
                return;
            }

            m_cal_dtShow.Rows[0][1] = ctl_cal_nudTxOff.Value.ToString();
            m_cal_dtShow.Rows[0][2] = ctl_cal_nudRxOff.Value.ToString();
            m_cal_dtShow.Rows[0][6] = ctl_cal_textRemark.Text;
            m_cal_dtShow.Rows[0][5] = ctl_cal_checkEff.Checked.ToString();
            m_cal_dtShow.Rows[0][7] = ctl_cal_nudF1.Value.ToString();
            m_cal_dtShow.Rows[0][8] = ctl_cal_nudF2.Value.ToString();
            m_cal_dtShow.Rows[0][9] = ctl_cal_nudRX1.Value.ToString();
            m_cal_dtShow.Rows[0][10] = ctl_cal_nudRX2.Value.ToString();
            m_cal_dtShow.Rows[0][11] = ctl_cal_nudRXSTEP.Value.ToString();
            m_cal_dtShow.Rows[0][12] = ctl_cal_nudProOffset.Value.ToString();
        }

        private void ctl_cal_btnStartCal_Click(object sender, EventArgs e)
        {
            if (m_cal_dtShow == null)
            {
                MessageBox.Show("请先下载校准");
                return;
            }

            if (!checkCalControl())
            {
                MessageBox.Show("请先设置频段参数和步进");
                return;
            }

            float limit = 0;
            if (!float.TryParse(ctl_cal_textRemark.Text, out limit))
            {
                MessageBox.Show("参考值非数字");
                return;
            }

            m_rowCalibration = m_cal_dtShow.NewRow();
            m_rowCalibration[0] = m_userObj.sEquID;
            m_rowCalibration[1] = ctl_cal_nudTxOff.Value.ToString();
            m_rowCalibration[2] = ctl_cal_nudRxOff.Value.ToString();

            m_rowCalibration[3] = 0;
            m_rowCalibration[4] = DateTime.Parse("1900-01-01");

            m_rowCalibration[6] = ctl_cal_textRemark.Text;
            m_rowCalibration[5] = ctl_cal_checkEff.Checked.ToString();
            m_rowCalibration[7] = ctl_cal_nudF1.Value.ToString();
            m_rowCalibration[8] = ctl_cal_nudF2.Value.ToString();

            m_rowCalibration[9] = ctl_cal_nudRX1.Value.ToString();
            m_rowCalibration[10] = ctl_cal_nudRX2.Value.ToString();
            m_rowCalibration[11] = ctl_cal_nudRXSTEP.Value.ToString();

            m_rowCalibration[12] = ctl_cal_nudProOffset.Value.ToString();

            m_running_mode = (int)Running_Mode.PIM_CAL;
            setEnable(false);
            ctl_cal_lblPower.Text = string.Format("功率: P1= --- dBm, P2= --- dBm");
            ctl_cal_textPass.Text = GDefine.ContentPass2;
            ctl_cal_textPass.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
            ctl_cal_textMax.Text = "";
            ctl_cal_textIMV.Text = "";

            double txoff = Convert.ToDouble(m_rowCalibration[1]);
            double rxoff = Convert.ToDouble(m_rowCalibration[2]);

            double f1 = Convert.ToDouble(m_rowCalibration[7]);
            double f2 = Convert.ToDouble(m_rowCalibration[8]);

            double rx1 = Convert.ToDouble(m_rowCalibration[9]);
            double rx2 = Convert.ToDouble(m_rowCalibration[10]);
            double step = Convert.ToDouble(m_rowCalibration[11]);
            double proOff = Convert.ToDouble(m_rowCalibration[12]);

            int mode = ctl_cal_mode.SelectedIndex;
            m_processObj.PIMProcessCalibration(f1, f2, rx1, rx2, step, txoff + proOff, rxoff, mode);
        }

        #endregion

        #region Config control Event

        private void ctl_config_btnNewVer_Click(object sender, EventArgs e)
        {
            FrmMConfigNew frmConfig = new FrmMConfigNew();
            frmConfig.ShowDialog();
        }

        void downloadCONFIGModuleData(object sender)
        {
            if (ctl_main_cbProCode.SelectedIndex == -1)
            {
                MessageBox.Show("当前实例未构造sProCode");
                return;
            }
            var cbVer = sender as ComboBox;
            if (cbVer.SelectedIndex == -1) return;

            if (m_cfg_cfgDataBuilder.construct(ctl_main_cbProCode.Text, cbVer.Text))
            {
                m_cfg_procodeObj = m_cfg_cfgDataBuilder.cProcodeINFO;
                m_cfg_dtConfigItems = ClsDataConfigBuilder.toTable(m_cfg_cfgDataBuilder.download());

                ctl_config_dgvData.DataSource = m_cfg_dtConfigItems.DefaultView;
                ctl_config_dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                for (int i = 0; i < ctl_config_dgvData.Columns.Count; i++)
                {
                    ctl_config_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                ctl_config_checkEff.Checked = m_cfg_procodeObj.bEffective;
                ctl_config_cbSpecVer.Text = m_cfg_procodeObj.sSpecVer;
                List<string> cols = ClsDataConfigBuilder.getConfigColNames();
                ctl_config_dgvData.Columns[cols[28]].Visible = false;
                ctl_config_dgvData.Columns[cols[29]].Visible = false;
                ctl_config_dgvData.Columns[cols[30]].Visible = false;
                ctl_config_dgvData.Columns[cols[31]].Visible = false;
            }
        }

        void updateCONFIGModuleData(object sender)
        {
            var cbVer = sender as ComboBox;
            if (cbVer.SelectedIndex == -1) return;
            if (ctl_main_cbProCode.SelectedIndex == -1) return;

            if (m_cfg_procodeObj == null) return;

            List<string> cols = ClsDataConfigBuilder.getConfigColNames();
            m_cfg_procodeObj.bEffective = ctl_config_checkEff.Checked;
            m_cfg_procodeObj.sSpecVer = ctl_config_cbSpecVer.Text;
            for (int i = 0; i < m_cfg_dtConfigItems.Rows.Count; i++)
            {
                m_cfg_dtConfigItems.Rows[i][cols[28]] = m_cfg_procodeObj.sConfigVer;
                m_cfg_dtConfigItems.Rows[i][cols[29]] = m_cfg_procodeObj.sSpecVer;
                m_cfg_dtConfigItems.Rows[i][cols[30]] = m_cfg_procodeObj.sEffTime;
                m_cfg_dtConfigItems.Rows[i][cols[31]] = m_cfg_procodeObj.bEffective;
            }

            m_cfg_cfgDataBuilder.construct(ctl_main_cbProCode.Text, cbVer.Text);
            if (m_cfg_cfgDataBuilder.update(ctl_config_checkEff.Checked, m_cfg_dtConfigItems))
            {
                MessageBox.Show("上传成功!");
            }
            else
            {
                MessageBox.Show("上传失败!");
            }
        }

        private void ctl_config_btnDownload_Click(object sender, EventArgs e)
        {
            downloadCONFIGModuleData(ctl_config_cbVerConfig);
        }

        private void ctl_config_btnUpload_Click(object sender, EventArgs e)
        {
            updateCONFIGModuleData(ctl_config_cbVerConfig);
        }

        private void ctl_config_btnInsert_Click(object sender, EventArgs e)
        {
            if (ctl_config_cbVerConfig.SelectedIndex == -1)
            {
                return;
            }
            if (ctl_config_dgvData.CurrentRow == null)
            {
                ctl_config_lblTips.Text = "提示: 请选择行!";
                return;
            }
            int n = ctl_config_dgvData.CurrentRow.Index;

            DataRow row = m_cfg_dtConfigItems.NewRow();
            row[20] = "dBm";
            row[26] = m_cfg_cfgDataBuilder.sVerSpec;
            row[27] = m_cfg_cfgDataBuilder.sVerConfig;
            row[28] = m_cfg_procodeObj.sEffTime;
            row[29] = ctl_config_checkEff.Checked.ToString();
            if (new FrmConfig(row).ShowDialog() == DialogResult.OK)
            {
                m_cfg_dtConfigItems.Rows.InsertAt(row, n);
                ctl_config_lblTips.Text = "提示: 插入成功!";
            }
            else
            {
                row.Delete();
                ctl_config_lblTips.Text = "提示: 插入已取消!";
            }
        }

        private void ctl_config_btnCopy_Click(object sender, EventArgs e)
        {
            if (ctl_config_cbVerConfig.SelectedIndex == -1)
            {
                return;
            }
            if (ctl_config_dgvData.CurrentRow == null)
            {
                ctl_config_lblTips.Text = "提示: 请选择行!";
                return;
            }
            int n = ctl_config_dgvData.CurrentRow.Index;

            DataRow row = m_cfg_dtConfigItems.NewRow();
            for (int i = 0; i < m_cfg_dtConfigItems.Columns.Count; i++)
                row[i] = m_cfg_dtConfigItems.Rows[n][i];

            if (new FrmConfig(row).ShowDialog() == DialogResult.OK)
            {
                m_cfg_dtConfigItems.Rows.Add(row);
                ctl_config_lblTips.Text = "提示: 复制并新增成功!";
            }
            else
            {
                row.Delete();
                ctl_config_lblTips.Text = "提示: 复制并新增已取消!";
            }
        }

        private void ctl_config_btnAdd_Click(object sender, EventArgs e)
        {
            if (ctl_config_cbVerConfig.SelectedIndex == -1)
            {
                return;
            }
            DataRow row = m_cfg_dtConfigItems.NewRow();
            row[20] = "dBm";
            row[26] = m_cfg_cfgDataBuilder.sVerSpec;
            row[27] = m_cfg_cfgDataBuilder.sVerConfig;
            row[28] = m_cfg_procodeObj.sEffTime;
            row[29] = ctl_config_checkEff.Checked.ToString();

            if (new FrmConfig(row).ShowDialog() == DialogResult.OK)
            {
                m_cfg_dtConfigItems.Rows.Add(row);
                ctl_config_lblTips.Text = "提示: 新增成功!";
            }
            else
            {
                row.Delete();
                ctl_config_lblTips.Text = "提示: 新增已取消!";
            }
        }

        private void ctl_config_btnModify_Click(object sender, EventArgs e)
        {
            if (ctl_config_cbVerConfig.SelectedIndex == -1)
            {
                return;
            }
            if (ctl_config_dgvData.CurrentRow == null)
            {
                ctl_config_lblTips.Text = "提示: 请选择行!";
                return;
            }
            int n = ctl_config_dgvData.CurrentRow.Index;

            if (new FrmConfig(m_cfg_dtConfigItems.Rows[n]).ShowDialog() == DialogResult.OK)
            {
                ctl_config_lblTips.Text = "提示: 修改成功!";
            }
            else
            {
                ctl_config_lblTips.Text = "提示: 修改已取消!";
            }
        }

        private void ctl_config_btnDelete_Click(object sender, EventArgs e)
        {
            if (ctl_config_cbVerConfig.SelectedIndex == -1)
            {
                return;
            }
            if (ctl_config_dgvData.CurrentRow == null)
            {
                ctl_config_lblTips.Text = "提示: 请选择行!";
                return;
            }
            if (MessageBox.Show("确认删除？", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                int n = ctl_config_dgvData.CurrentRow.Index;
                m_cfg_dtConfigItems.Rows.RemoveAt(n);

                ctl_config_lblTips.Text = "提示: 删除成功!";
            }
            else
            {
                ctl_config_lblTips.Text = "提示: 删除已取消!";
            }
        }

        private void ctl_config_cbVerConfig_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void ctl_config_dgvData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            ctl_config_btnModify_Click(sender, e);
        }

        #endregion

        #region Setup control Event

        bool uploadSetupData()
        {



            return true;
        }

        private void ctl_setup_btnOk_Click(object sender, EventArgs e)
        {
            if (ctl_setup_text1.Text == "" || ctl_setup_text4.Text == "" || ctl_setup_text5.Text == "" || ctl_setup_text10.Text == "")
            {
                MessageBox.Show("请输入完整!");
                return;
            }

            DataRow dr;
            if (ctl_setup_btnNewVer.Enabled)
            {
                dr = m_setup_dtShow.NewRow();

            }
            else if (ctl_setup_btnModify.Enabled)
            {
                int n = ctl_setup_dgvData.CurrentRow.Index;
                dr = m_setup_dtShow.Rows[n];
            }
            else
            {
                return;
            }

            dr[0] = ctl_setup_text1.Text;
            dr[1] = ctl_setup_nud2.Value.ToString();
            dr[2] = ctl_setup_check3.Checked;
            dr[3] = ctl_setup_text4.Text;
            dr[4] = ctl_setup_text5.Text;
            dr[5] = ctl_setup_check6.Checked.ToString();
            dr[6] = ctl_setup_check7.Checked.ToString();
            dr[7] = ctl_setup_nud8.Value.ToString("0.0");
            dr[8] = ctl_setup_check9.Checked.ToString();
            dr[9] = ctl_setup_text10.Text;

            if (ctl_setup_btnNewVer.Enabled)
            {
                DataRow[] lstRow = m_setup_dtShow.Select(m_setup_dtShow.Columns[7].ColumnName + "='" + ctl_setup_nud8.Value.ToString("0.0") + "'");
                if (lstRow != null && lstRow.Length > 0)
                {
                    MessageBox.Show("版本重复,请重新输入");
                    return;
                }
                m_setup_dtShow.Rows.Add(dr);
            }

            ctl_setup_gbItems.Visible = false;
            ctl_setup_btnModify.Enabled = true;
            ctl_setup_btnNewVer.Enabled = true;
            ctl_setup_dgvData.Enabled = true;
            ctl_setup_btnDel.Enabled = true;
        }

        private void ctl_setup_btnCancel_Click(object sender, EventArgs e)
        {
            ctl_setup_gbItems.Visible = false;
            ctl_setup_btnModify.Enabled = true;
            ctl_setup_btnNewVer.Enabled = true;
            ctl_setup_dgvData.Enabled = true;
            ctl_setup_btnDel.Enabled = true;
        }

        private void ctl_setup_btnNewVer_Click(object sender, EventArgs e)
        {
            if (ctl_main_cbProCode.Text == "")
            {
                return;
            }

            if (m_setup_dtShow == null)
            {
                return;
            }

            float fMaxVer = float.MinValue;
            for (int i = 0; i < m_setup_dtShow.Rows.Count; i++)
            {
                float ver = Convert.ToSingle(m_setup_dtShow.Rows[i][7]);
                if (ver > fMaxVer)
                {
                    fMaxVer = ver;
                }
            }
            if (fMaxVer == float.MinValue)
            {
                MessageBox.Show("这是此产品代码的第一个设置版本!");
                fMaxVer = 1.0f;
            }
            else
            {
                fMaxVer += 0.1f;
            }

            ctl_setup_nud8.Value = Convert.ToDecimal(fMaxVer);

            ctl_setup_text1.Text = "";
            ctl_setup_nud2.Value = 0;
            ctl_setup_check3.Checked = false;
            ctl_setup_text4.Text = "";
            ctl_setup_text5.Text = "";
            ctl_setup_check6.Checked = false;
            ctl_setup_check7.Checked = false;
            ctl_setup_check9.Checked = false;
            ctl_setup_text10.Text = "";
            ctl_setup_nud8.Enabled = false;
            ctl_setup_gbItems.Visible = true;
            ctl_setup_btnModify.Enabled = false;
            ctl_setup_btnDel.Enabled = false;
            ctl_setup_btnNewVer.Enabled = true;
        }

        private void ctl_setup_btnModify_Click(object sender, EventArgs e)
        {
            if (ctl_main_cbProCode.Text == "")
            {
                return;
            }

            if (ctl_setup_dgvData.CurrentRow == null)
            {
                ctl_setup_lblTips.Text = "提示: 请选择行!";
                return;
            }
            int n = ctl_setup_dgvData.CurrentRow.Index;

            ctl_setup_text1.Text = m_setup_dtShow.Rows[n][0].ToString();
            ctl_setup_nud2.Value = Convert.ToDecimal(m_setup_dtShow.Rows[n][1].ToString());
            ctl_setup_check3.Checked = Convert.ToBoolean(m_setup_dtShow.Rows[n][2].ToString());
            ctl_setup_text4.Text = m_setup_dtShow.Rows[n][3].ToString();
            ctl_setup_text5.Text = m_setup_dtShow.Rows[n][4].ToString();
            ctl_setup_check6.Checked = Convert.ToBoolean(m_setup_dtShow.Rows[n][5].ToString());
            ctl_setup_check7.Checked = Convert.ToBoolean(m_setup_dtShow.Rows[n][6].ToString());
            ctl_setup_nud8.Value = Convert.ToDecimal(m_setup_dtShow.Rows[n][7].ToString());
            ctl_setup_check9.Checked = Convert.ToBoolean(m_setup_dtShow.Rows[n][8].ToString());
            ctl_setup_text10.Text = m_setup_dtShow.Rows[n][9].ToString();

            ctl_setup_nud8.Enabled = false;
            ctl_setup_gbItems.Visible = true;
            ctl_setup_btnModify.Enabled = true;
            ctl_setup_btnNewVer.Enabled = false;
            ctl_setup_dgvData.Enabled = false;
            ctl_setup_btnDel.Enabled = false;
        }

        private void ctl_setup_btnDel_Click(object sender, EventArgs e)
        {
            if (ctl_main_cbProCode.Text == "")
            {
                return;
            }

            if (ctl_setup_dgvData.CurrentRow == null)
            {
                ctl_setup_lblTips.Text = "提示: 请选择行!";
                return;
            }

            int n = ctl_setup_dgvData.CurrentRow.Index;
            if (MessageBox.Show("确认删除？", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                m_setup_dtShow.Rows.RemoveAt(n);
            }
        }

        void downloadSetupData()
        {
            string error = "";
            m_setup_builder.construct(ctl_main_cbProCode.Text);
            m_setup_dtShow = m_setup_builder.download(ref error);
            if (m_setup_dtShow == null)
            {
                MessageBox.Show(error);
                return;
            }

            ctl_setup_dgvData.DataSource = m_setup_dtShow;
            for (int i = 0; i < ctl_setup_dgvData.Columns.Count; i++)
            {
                ctl_setup_dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void ctl_setup_btnDownload_Click(object sender, EventArgs e)
        {
            downloadSetupData();
        }

        bool updateSetupData()
        {
            if (m_setup_dtShow == null || m_setup_dtShow.Rows.Count == 0) return false;

            string error = "";
            if (!m_setup_builder.upload(m_setup_dtShow, ref error))
            {
                MessageBox.Show(error);
                return false;
            }
            else
            {
                MessageBox.Show("上传成功");
                return true;
            }
        }

        private void ctl_setup_btnUpload_Click(object sender, EventArgs e)
        {
            updateSetupData();
        }

        private void ctl_setup_dgvData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            ctl_setup_btnModify_Click(null, null);
        }

        #endregion

        #region Running

        private void setEnable(bool enable)
        {
            if (!enable)
            {
                m_fMax = float.MinValue;
                ctl_main_lblReuslt.Text = "---";
            }
            ctl_cal_btnStartCal.Enabled = enable;
            ctl_cal_btnModify.Enabled = enable;
            groupBox1.Enabled = enable;
            btn_pim_ok.Enabled = enable;
            btn_engineering_ok.Enabled = enable;
            ctl_cal_btnDownload.Enabled = enable;
            ctl_config_btnDownload.Enabled = enable;
            ctl_setup_btnDownload.Enabled = enable;
            ctl_cal_btnUpload.Enabled = enable;
            ctl_config_btnUpload.Enabled = enable;
            ctl_setup_btnUpload.Enabled = enable;
        }

        private void ctl_main_tbProSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;

            if (tab_module.SelectedIndex == 0)
            {
                btn_pim_ok_Click(sender, e);
            }
        }

        private void btn_pim_ok_Click(object sender, EventArgs e)
        {
            if (tab_module.Enabled == false)
            {
                MessageBox.Show("请设置配置文件!");
                return;
            }

            if (ctl_main_tbProSN.Text.Trim() == "")
            {
                MessageBox.Show("请输入产品SN!");
                return;
            }
            m_processObj.PIMTestModeSet(m_ModTestMode);
            ClsDataProduct productObj = new ClsDataProduct();
            productObj.sProductSN = ctl_main_tbProSN.Text;
            productObj.sLocalStep = ctl_main_textLocalStep.Text;

            #region 匹配产品代码
            if (!m_processObj.PIMProcessMatchProcode(productObj))
            {
                MessageBox.Show("该条码无法匹配产品代码!");
                return;
            }


            if (!m_processObj.PIMStepCheck(productObj))
            {
                MessageBox.Show("已取消测试！");
                return;
            }

            if (ctl_main_cbProCode.Text == productObj.sProcode)
            {

                IniFile.SetFileName(Application.StartupPath + "\\JcVersion.ini");
                string Vercheck = IniFile.IniReadValue("VersionRecord", productObj.sProcode, "");
                if (Vercheck == "")
                {
                    MessageBox.Show("此产品代码无版本记录,请重新选择!");
                    return;
                }

                if (Vercheck != ctl_pim_cbVerConfig.Text)
                {
                    MessageBox.Show("此产品代码版本记录不匹配,请重新选择!");
                    return;
                }
                ctl_pim_cbVerConfig.Text = Vercheck;
            }
            else
            {
                if (ctl_main_cbProCode.Items.IndexOf(productObj.sProcode) < 0)
                {
                    initDataConfig();
                    if (ctl_main_cbProCode.Items.IndexOf(productObj.sProcode) < 0)
                    {
                        MessageBox.Show("此产品代码还没有配置过！");
                        return;
                    }
                }
                ctl_main_cbProCode.Text = productObj.sProcode;
                MessageBox.Show("当前产品为第一次测试,请手动选择配置版本号");
                ctl_pim_cbVerConfig.Enabled = true;
                return;
            }
            productObj.sConfigVer = ctl_pim_textVerSpec.Text;

            ctl_main_textProcodeName.Text = productObj.sProcodeName;
            ctl_main_textTestStep.Text = productObj.sPIMTestStep;
            if (m_pim_dtShow == null || m_pim_dtShow.Rows.Count == 0)
            {
                MessageBox.Show("产品代码的配置为空或不存在!");
                return;
            }
            #endregion

            initPIMShowTable();


            m_running_mode = (int)Running_Mode.PIM;
            productObj.iMode = (int)Running_Mode.PIM;
            ctl_pim_tbLog.Text = "";
            ctl_main_lblReuslt.Text = "PASS";
            m_isProcessStart = true;
            setEnable(false);



            if (m_processObj.PIMProcessConfig(m_pim_lstCfgData, productObj, m_userObj))
            {
                m_processObj.PIMProcessStrart();
            }
        }

        private void btn_engineering_ok_Click(object sender, EventArgs e)
        {
            if (ctl_main_tbProSN.Text.Trim() == "")
            {
                MessageBox.Show("请输入产品SN!");
                return;
            }
            m_processObj.PIMTestModeSet(m_ModTestMode);

            ClsDataProduct productObj = new ClsDataProduct();
            productObj.sProductSN = ctl_main_tbProSN.Text;
            productObj.sProcode = ctl_main_cbProCode.Text;
            productObj.sLocalStep = ctl_main_textLocalStep.Text;

            if (m_eng_dtShow == null || m_eng_dtShow.Rows.Count == 0)
            {
                MessageBox.Show("产品代码的配置为空或不存在!");
                return;
            }

            for (int i = 0; i < ctl_eng_dgvData.Rows.Count; i++)
            {
                m_eng_lstCfgData[i].Enable = (bool)ctl_eng_dgvData.Rows[i].Cells[0].Value;
            }

            initENGShowTable();
            m_running_mode = (int)Running_Mode.ENG;
            productObj.iMode = (int)Running_Mode.ENG;
            ctl_eng_tbLog.Text = "";
            ctl_main_lblReuslt.Text = "PASS";
            m_isProcessStart = true;
            setEnable(false);

            if (m_processObj.PIMProcessConfig(m_eng_lstCfgData, productObj, m_userObj))
            {
                m_processObj.PIMProcessStrart();
            }
        }

        #endregion

        #region TIPS

        public bool Tips(string text, int btn = 1)
        {
            bool ret = false;
            this.Invoke(new ThreadStart(delegate
            {
                MessageBoxButtons msgBtn = btn == 1 ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK;
                if (MessageBox.Show(text, "提示", msgBtn, MessageBoxIcon.Exclamation) == DialogResult.OK)
                {
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }));
            return ret;
        }

        public bool AutoClosingTips(string text, int timeout)
        {
            bool ret = false;
            this.Invoke(new ThreadStart(delegate
            {
                AutoClosingMessageBox.Show(text, "提示", timeout);
                ret = true;
            }));
            return ret;
        }

        public int selectTips(string text)
        {
            int ret = 1;
            this.Invoke(new ThreadStart(delegate
            {
                FrmRetry frmTips = new FrmRetry(false, text);
                DialogResult dr = frmTips.ShowDialog();
                if (dr == DialogResult.No)
                {
                    ret = -1;
                }
                else if (dr == DialogResult.Retry)
                {
                    ret = 1;
                }
                else if (dr == DialogResult.Ignore)
                {
                    ret = 0;
                }
            }));
            return ret;
        }

        #endregion

        private void DevicesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmDeviceMod frmDeveice = new FrmDeviceMod();
            frmDeveice.ShowDialog();
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void 管理用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES.ADMIN))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            FrmUserManage dlgUser = new FrmUserManage(m_userObj.aUser, true);
            dlgUser.ShowDialog();
        }

        private void tab_module_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (tab_module.SelectedTab == tabPage2)
            {
                if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES_MOD.ENG))
                {
                    MessageBox.Show("权限不足！");
                    e.Cancel = true;
                }
            }
            else if (tab_module.SelectedTab == tabPage3)
            {
                if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES_MOD.CALIBRATION))
                {
                    MessageBox.Show("权限不足！");
                    e.Cancel = true;
                }
            }
            else if (tab_module.SelectedTab == tabPage4)
            {
                if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES_MOD.CONFIG))
                {
                    MessageBox.Show("权限不足！");
                    e.Cancel = true;
                }
            }
            else if (tab_module.SelectedTab == tabPage5)
            {
                if (!m_userObj.HavePower(clsPowerManage.POWER_FEAFTURES_MOD.SETUP))
                {
                    MessageBox.Show("权限不足！");
                    e.Cancel = true;
                }
            }

        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmChangePwd frmpwd = new FrmChangePwd(m_userObj);
            frmpwd.ShowDialog();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int num = int.Parse(WatingForm.GetLastInputTime().ToString());
            if (num >= 180000)
            {
                timer1.Stop();
                // 重新登陆ToolStripMenuItem_Click(null, null);
                this.Hide();
                FrmLogin frmlgn = new FrmLogin(m_userObj);
                frmlgn.ControlBox = true;
                if (frmlgn.ShowDialog() == DialogResult.OK)
                {
                    toolStripStatusLabel2.Text = string.Format("员工号：{0}      姓名：{1}      账号类型：{2}",
                                                m_userObj.sUserID, m_userObj.sUser, m_userObj.sRemark);
                    toolStripStatusLabel3.Text = string.Format("设备IP:{0}      管理部门:质量", m_userObj.sEquID);
                    this.Show();
                    timer1.Start();
                }
                else
                    this.Close();
            }
        }

        private void 设备调试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rflight.FrmDeviceDebug frm = new rflight.FrmDeviceDebug();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void 测试类型ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmTestMode frm = new FrmTestMode(m_ModTestMode);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcOther.ini");
                IniFile.IniWriteValue("Login", "ModTestMode", ((int)frm.m_mode).ToString());
                m_ModTestMode = frm.m_mode;
                if (m_ModTestMode == ModTestMode.First)
                {
                    toolStripStatusLabel1.Text = "一次互调测试";
                }
                else
                {
                    toolStripStatusLabel1.Text = "二次互调测试";
                }
            }
            frm.Dispose();
        }


    }

    public class AutoClosingMessageBox
    {
        System.Threading.Timer _timeoutTimer;
        string _caption;

        AutoClosingMessageBox(string text, string caption, int timeout)
        {
            _caption = caption;
            _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
                null, timeout, System.Threading.Timeout.Infinite);

            using (_timeoutTimer)
                MessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        public static void Show(string text, string caption, int timeout)
        {
            new AutoClosingMessageBox(text, caption, timeout);
        }

        void OnTimerElapsed(object state)
        {
            IntPtr mbWnd = FindWindow("#32770", _caption);
            if (mbWnd != IntPtr.Zero)
                SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            _timeoutTimer.Dispose();
        }

        const int WM_CLOSE = 0x0010;
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    }

    public class WatingForm
    {

        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO
        {
            ///

            /// 设置结构体块容量
            ///

            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }

        [DllImport("user32.dll")]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        public static long GetLastInputTime()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
            if (!GetLastInputInfo(ref vLastInputInfo))
            {
                return 0;
            }
            else
            {
                long count = Environment.TickCount - (long)vLastInputInfo.dwTime;
                //long icount = count / 1000;
                return count;
            }
        }
    }
}
